package com.hoyin.lightctrl_esp8266;

import android.app.Activity;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import static androidx.constraintlayout.motion.utils.Oscillator.TAG;

public class SocketConnectThread extends Thread{
	private InetAddress mIpAddress;
	private int mClientPort;
	private Socket mSocket;
	private OutputStream mOutStream;
	private InputStream mInStream;
	private SocketReceiveThread mReceiveThread;
	private Activity mActivity;
	public boolean connect_status = false;

	public SocketConnectThread(Activity activity, String ip_address, String port_number) throws UnknownHostException {
		mIpAddress = InetAddress.getByName(ip_address);
		mClientPort = Integer.valueOf(port_number).intValue();
		mActivity = activity;
	}

	public OutputStream getOutStream(){
		return mOutStream;
	}

	public void run(){
		try {
			//指定ip地址和端口号
			mSocket = new Socket(mIpAddress, mClientPort);
			mReceiveThread = new SocketReceiveThread(mActivity, mSocket);

			if(mSocket != null){
				//获取输出流、输入流
				mOutStream = mSocket.getOutputStream();
				mInStream = mSocket.getInputStream();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
		connect_status = true;
		Log.i(TAG,"connect success");
	}


	public void closeConnection(){
		try {
			if (mOutStream != null) {
				mOutStream.close(); //关闭输出流
				mOutStream = null;
			}
			if (mInStream != null) {
				mInStream.close(); //关闭输入流
				mInStream = null;
			}
			if(mSocket != null){
				mSocket.close();  //关闭socket
				mSocket = null;
			}
			connect_status = false;
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(mReceiveThread != null){
			mReceiveThread.interrupt();
			mReceiveThread = null;
		}
	}
}
